<?php


namespace app\community\dbUtil;


use app\cms\model\buildModel;
use think\db\ConnectionInterface;
use think\facade\Db;

class buildTable
{
    // 生成 数据库表
    protected string $tableName = '';
    protected string $error = '';

    protected ConnectionInterface $db;

    public function __construct(protected tableField $field)
    {}

    /**
     * 生成数据库表
     * @return $this
     */
    public function makeTable(): static
    {
        if ($this->tableName === '') {
            $this->error = '表名不能为空';
            return $this;
        }
        $this->db -> execute($this->buildCreateTableSql());
        return $this;
    }

    protected function buildCreateTableSql(): string
    {
        // 创建数据库表sql
        $sql = "
            create table `{$this -> tableName}` (
                {$this->field -> buildTableFieldSql()}
            ) ENGINE = innodb
            DEFAULT CHARSET = utf8mb4;
        ";

        return str_replace("\r\n", "", $sql);
    }

    public function buildAlterFieldSql()
    {
        // 生成添加字段sql
        $column = $this->field -> buildAlterFieldSql($this->tableName);
        // 执行sql
        array_walk($column, function ($field) {
            $this->db -> execute($field);
        });
    }

    /**
     * @return string
     */
    public function getTableName(): string
    {
        return $this->tableName;
    }

    /**
     * @param string $tableName
     * @return static
     */
    public function setTableName(string $tableName): static
    {
        $this->tableName = $tableName;
        $buildTable = new buildModel(table: $this->tableName);
        $this->db = Db::connect($buildTable -> getConnection());
        return $this;
    }

    /**
     * @return string
     */
    public function getError(): string
    {
        return $this->error;
    }
}